<?php

function rpc( $json_request ) {
    global $PARAPARA;

    $req_param = $json_request->param;

    $account = $PARAPARA->fetch_account();

    if( ( $account == null) && 
        ( $PARAPARA->config_get('LINKROLL',  'ALLOW_ANONYMOUS') != 'true') ) {
        return new RPC_Error($json_request->operation, "AUTH", "Not authorized to post annonymously");
    }


    if( $account ) {
        $submitter    = $PARAPARA->get_screen_name();
        $submitter_id = $PARAPARA->get_uid();
    } 
    else {
        return new RPC_Error($json_request->operation, "AUTH", "Annonymous posting broken for now");
    }

    $MAX_URL_LEN      = 250;
    $MAX_HEADLINE_LEN = 250;

    $url = $req_param->url;
    if( !is_string( $url ) || !strlen( $url ) || 
        ( strlen( $url ) > $MAX_URL_LEN ) )
        return new RPC_Error( $json_request->operation, "PARAM", "Urlen er enten tom eller for lang" );

    if(!Helpers::validate_url( $url ))
        return new RPC_Error( $json_request->operation, "PARAM", "Urlen kan ikke valideres" );

    $headline = $req_param->headline;
    if( !is_string( $headline ) || !strlen( $headline ) || 
        ( strlen( $headline ) > $MAX_HEADLINE_LEN ) )
        return new RPC_Error( $json_request->operation, "PARAM", "Headlinen er enten tom eller for lang" );

    $category_id = $req_param->category_id;
    if(!is_numeric($category_id))
        $category_id = 1;

    $approved = $account->is_admin() ? 1: 0;

    $ip          = $PARAPARA->remote_addr;

    $dbl = $PARAPARA->dblayer;

    if( $req_param->preview_only ) {
        $link = new LinkRollLink( 0, $url, $headline, $submitter, $submitter_id, $category_id, 0, 1, $ip);
        $category   = $dbl->get_linkroll_category( $category_id );

        $rpc_retval = array( 'status' => 'ok',
                             'html'   => $link->as_html( array( 'category' => $category) )
            );
    }

    else {
        $status = $dbl->create_linkroll_link( $url, $headline, $submitter, $submitter_id, $category_id, $approved, $ip );

        if($status == 'ok') {
            $linkroll    = $dbl->get_linkroll();
        }


        $rpc_retval = array( 'status'      => $status, 
                             'html'        => $linkroll->as_html( array() ), 
                             'link_count'  => $linkroll->link_count,
                             'newest_id'   => $linkroll->newest_id
            );
    }
    return new RPC_Response( $json_request->operation, $rpc_retval );

  }

return rpc( $json_request );
?>